package com.siyuanren.gcocp.common.file;

import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.slf4j.LoggerFactory;

import java.io.File;

/**
 * Created by   guwr
 * Project_name education-api-parent
 * Path         com.siyuanren.gcocp.common.file.FileManager
 * Date         2017/6/15
 * Time         11:32
 * Description
 */
public class FileManager implements FileManagerConfig {
    private static final long serialVersionUID = 1L;
    private static org.slf4j.Logger logger = LoggerFactory.getLogger(FileManager.class);
    private static TrackerClient trackerClient;
    private static TrackerServer trackerServer;
    private static StorageServer storageServer;
    private static StorageClient storageClient;

    static {
        try {
            String classPath = new File(FileManager.class.getResource("/").getFile()).getCanonicalPath();
            String fdfsClientConfigFilePath = classPath + File.separator + CLIENT_CONFIG_FILE;
            ClientGlobal.init(fdfsClientConfigFilePath);

            trackerClient = new TrackerClient();
            trackerServer = trackerClient.getConnection();

            storageClient = new StorageClient(trackerServer, storageServer);
            logger.info("storageClient = {}", storageClient);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * <strong>方法概要： 文件上传</strong> <br>
     * <strong>创建时间： 2016-9-26 上午10:26:11</strong> <br>
     *
     * @param file
     * @return fileAbsolutePath
     * @author Wang Liang
     */
    public static String upload(FastDFSFile file, NameValuePair[] valuePairs) {
        String[] uploadResults = null;
        try {
            logger.info("file = {}", file);
            logger.info("valuePairs = {}", valuePairs);
            uploadResults = storageClient.upload_file(file.getContent(), file.getExt(), valuePairs);
            logger.info("uploadResults = {}", uploadResults);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String groupName = uploadResults[0];
        String remoteFileName = uploadResults[1];

        String fileAbsolutePath = PROTOCOL
                + TRACKER_NGNIX_ADDR
                //+ trackerServer.getInetSocketAddress().getHostName()
                //+ SEPARATOR + TRACKER_NGNIX_PORT
                + SEPARATOR + groupName
                + SEPARATOR + remoteFileName;

        return groupName + SEPARATOR + remoteFileName;
//        return fileAbsolutePath;
    }
}
